<template>
    <el-row class="login-container" justify="center" :align="`middle`">
      <el-card style="max-width: 480px;">
        <template #header>
          <div class="card-header">
            <img src="../../../public/login-head.png">
          </div>
        </template>
        <div class="jump-link">
          <el-link type="primary" @click="handleChange">{{ formtype ?'返回登陆':'注册账号' }}</el-link>
        </div>
        <el-form :model="loginform" :rules="rules" ref="loginFormRef" >
          <el-form-item prop="userName">
            <el-input  v-model="loginform.userName" placeholder="手机号" prefix-icon="UserFilled"></el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input v-model="loginform.passWord" type="passWord" placeholder="密码" prefix-icon="Lock"></el-input>
          </el-form-item>
          <el-form-item v-if="formtype" prop="validCode">
            <el-input v-model="loginform.validCode"  placeholder="验证码" prefix-icon="Lock">
              <template #append>
              <span @click="coundownChange">{{ countdown.validText }}</span>
          </template>
            </el-input>
          </el-form-item>
          <el-button type="primary" style="width: 100%;" @click="submitForm(loginFormRef)">
            {{ formtype ?'注册账号':'登录' }}
          </el-button>
        </el-form>
      </el-card>
    </el-row>
  </template>
  
  <script lang="ts" setup name="Mlogin">
import useCountStore from '../m-store/stroe';
import { reactive, ref } from 'vue';
import {getCode,userAuthentication,login, menuPermissions} from '../m-tool/m-api/Mapi'
import { useRouter } from 'vue-router';

const formtype=ref(0)
const router=useRouter()

const loginform = reactive({
    userName:'',
    passWord:'',
    validCode:''
  })

const countdown=reactive({
  validText:'获取验证码',
  time:60
})

const loginFormRef = ref()
const PhoneType=/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

const PassWordType=/^[a-zA-Z0-9_-]{4,16}$/

function validateUser(rule:any,value:string,callbck:any){

  if(value===''){
    callbck(new Error('请输入手机号'))
  }else{
    PhoneType.test(value) ? callbck() :callbck(new Error('手机号格式不对，请重新输入'))
  }

}
function validatePass(rule:any,value:string,callbck:any){
   if(value===''){
    callbck(new Error('请输入密码'))
  }else{
    PassWordType.test(value) ? callbck() :callbck(new Error('密码格式不对，请重新输入'))
  }

}


const rules=reactive({
  userName:[{ validator:validateUser, trgger:'blur'}],
  passWord:[{ validator:validatePass, trgger:'blur'}]
})
 
 let flag=false

function handleChange(){
  formtype.value=formtype.value ? 0 :1
}

function coundownChange(){

  
  if(!PhoneType.test(loginform.userName)||!loginform.userName){
    return ElMessage({
      message:'手机号输入有误',
      type:'warning',
    })
  }

if(!PassWordType.test(loginform.passWord)||!loginform.passWord){
  return ElMessage({
      message:'密码',
      type:'warning',
    })
  }

  if(flag) return

  const colock=setInterval(()=>{
    if(countdown.time<=0){
      countdown.time=60
      countdown.validText='获取验证码'
      flag=false
      clearInterval(colock)
    }else{
          countdown.time-=1
    countdown.validText=`剩余${countdown.time}`
    }

  },1000)
  flag=true
  getCode({tel:loginform.userName}).then(({data})=>{
    console.log(data,'data');
    if(data.code===10000){
      ElMessage.success('发送成功')
    }
    
  })
}
async function submitForm(formEl:any){
    if (!formEl) return
    await formEl.validate((valid:any, fields:any) => {
      if (valid) {
        console.log(loginform,'submit!')

        if(formtype.value){

          userAuthentication(loginform).then(({data})=>{
            if(data.code==10000){
              ElMessage.success('注册成功，请登录')
              formtype.value=0
            }
          })

        }else{
      
          login(loginform).then(({data})=>{
            if(data.code==10000){
              ElMessage.success('登录成功')
              localStorage.setItem('pz_token',data.data.token)
              localStorage.setItem('pz_userInfo',JSON.stringify(data.data.userInfo))
              // menuPermissions().then(({data})=>{
              // const conststore=useCountStore() 
              // conststore.dynamicMenu('dynamicMenu',data.data)
            router.push('/')
              // })
              
            }
          })

        }
      } else {
        console.log('error submit!', fields)
      }
    })
}

  </script>
  
  <style scoped lang="less">

  :deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
  </style>